package com.huanghe.mgr;

import com.alibaba.fastjson.JSONObject;
import com.huanghe.util.HttpDeleteWithBody;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;

public class JobMgr {
    private static final String CLUSTER_ID = "11b3bb4c-b22a-11ec-ab57-0255ac100044";

    private static final String ENDPOINT_ID = "cce.cn-southwest-2.myhuaweicloud.com";

    private static final String DELETE_URI = "/apis/batch/v1/namespaces/%s/jobs/%s";

    private static final String CREATE_URI = "/apis/batch/v1/namespaces/%s/jobs";

    private static final String STATUS_URI = "/apis/batch/v1/namespaces/%s/jobs/%s/status";

    /**
     * 删除job
     *
     * @param token     token
     * @param namespace k8s命名空间
     * @param name      job名称
     * @throws IOException 异常
     */
    public void deleteJob(String token, String namespace, String name) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 设置url
        String uri = String.format(DELETE_URI, namespace, name);
        String url = "https://" + CLUSTER_ID + "." + ENDPOINT_ID + File.separator + uri;
        String resString = "";
        try {
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            // 设置header信息
            httpDelete.setHeader(new BasicHeader("Content-Type", "application/json"));
            httpDelete.setHeader(new BasicHeader("X-Auth-Token", token));
            // 设置请求消息
            JSONObject json = new JSONObject();
            json.put("kind", "DeleteOptions");
            json.put("apiVersion", "v1");
            json.put("propagationPolicy", "Background");
            httpDelete.setEntity(new StringEntity(json.toJSONString()));
            // 执行请求
            response = httpclient.execute(httpDelete);
            System.out.println("请求返回的状态码：" + response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度：" + content.length());
                System.out.println("返回的内容：" + content);
            }
        } catch (Exception e) {
            System.out.println("系统错误：" + e.getMessage() + "---" + e.toString() + "====" + e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }

    /**
     * 创建Job
     *
     * @param namespace      名称空间
     * @param requestBodyStr Job创建请求参数
     * @param token token
     * @throws IOException
     */
    public void createJob(String namespace, String requestBodyStr, String token) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 设置url
        String uri = String.format(CREATE_URI, namespace);
        String url = "https://" + CLUSTER_ID + "." + ENDPOINT_ID + File.separator + uri;
        String resString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            // 设置header信息
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
            httpPost.setHeader(new BasicHeader("X-Auth-Token", token));

            // 装填参数
            StringEntity s = new StringEntity(requestBodyStr, "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            // 设置参数到请求对象中
            httpPost.setEntity(s);

            // 执行请求
            response = httpclient.execute(httpPost);
            System.out.println("请求返回的状态码：" + response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 201) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度：" + content.length());
                System.out.println("返回的内容：" + content);
            }
        } catch (Exception e) {
            System.out.println("系统错误：" + e.getMessage() + "---" + e.toString() + "====" + e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
    }

    /**
     * 获取Job的状态
     * @param namespace 命名空间
     * @param name job的名称
     * @param token token
     */
    public JSONObject getJobStatus(String namespace,String name,String token) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 设置url
        String uri = String.format(STATUS_URI, namespace, name);
        String url = "https://" + CLUSTER_ID + "." + ENDPOINT_ID + File.separator + uri;
        String resString = "";
        try {
            HttpGet httpGet = new HttpGet(url);
            // 设置header信息
            httpGet.setHeader(new BasicHeader("Content-Type", "application/json"));
            httpGet.setHeader(new BasicHeader("X-Auth-Token", token));

            // 执行请求
            response = httpclient.execute(httpGet);
            System.out.println("请求返回的状态码：" + response.getStatusLine().getStatusCode());
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("内容长度：" + content.length());
                System.out.println("返回的内容：" + content);
                JSONObject jsonObject1 =JSONObject.parseObject(content);
                return jsonObject1;
            }
        } catch (Exception e) {
            System.out.println("系统错误：" + e.getMessage() + "---" + e.toString() + "====" + e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return null;
    }

}
